package com.seu.me.test.policy;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.List;

/**
 * @author liangfeihu
 * @since 2019/11/25 20:21
 */
@Slf4j
public class TransXmlInfoTest2 {
    public static void main(String[] args) {
        String fileContent = readFileContent("/Users/liangfeihu/projects/gitee/myown/multi-learning/xml/Out_SGP191200000000110_20191125193006.xml");
        TransXmlInfo transXmlInfo = convertToJavaBean(fileContent, TransXmlInfo.class);
        System.out.println(transXmlInfo);

        int cnt = 0;
        List<TransXmlInfo.PolicyInfo> policyInfoList = transXmlInfo.getPolicyData().getPolicyInfoList();
        for (TransXmlInfo.PolicyInfo policyInfo : policyInfoList) {
            TransXmlInfo.ContData contData = policyInfo.getContData();
            if (contData == null) {
                System.out.println(JSONObject.toJSONString(policyInfo));
                continue;
            }
            List<TransXmlInfo.ContInfo> contInfoList = contData.getContInfoList();
            if (contInfoList == null || contInfoList.size() < 1) {
                System.out.println(JSONObject.toJSONString(policyInfo));
                continue;
            }
            for (TransXmlInfo.ContInfo contInfo : contInfoList) {
                System.out.println(cnt++);
            }
        }
    }

    /**
     * xml转换成JavaBean
     *
     * @param xml
     * @param c
     * @return
     */
    public static <T> T convertToJavaBean(String xml, Class<T> c) {
        if (StringUtils.isEmpty(xml)) {
            return null;
        }
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            log.error("xml to JavaBean ex.", e);
        }
        return t;
    }

    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }
}
